<?php
declare(strict_types=1);

namespace App\AdminApi\Api;

use App\AdminApi\AdminApiBasicsController;
use App\Common\Extend\Ai\Ai;
use App\Sys;
use Zms\Guard\Auth;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Zms\Unit\Json;

#[
    Controller(prefix: "/admin-api/ai", server: self::SERVER),
    Auth(guard: self::GUARD, label: ['其他设置'], app: self::APP)
]
class AiController extends AdminApiBasicsController
{
    #[Inject]
    protected Ai $ai;

    #[
        PostMapping('chat'),
        Auth(label: ['Ai对话'], sign: 'ai.chat', process: false)
    ]
    public function chat(ResponseInterface $response): void
    {
        if ($this->isLogin()) {
            $open = Sys::conf('ai.open/int');
            if ($open === 1) {
                $data = $this->request->inputs(['message', 'chat_id']);
                $response->write('data: ' . Json::encode(['code' => 200, 'stage' => 'start']));
                $this->ai->chat($data, function ($msg) use ($response) {
                    if (!is_null($msg)) {
                        $response->write('data: ' . Json::encode(['code' => 200, 'data' => $msg, 'stage' => 'output']));
                    }
                });
                $response->write('data: ' . Json::encode(['code' => 200, 'stage' => 'end']));
            } else {
                $response->write('data: ' . Json::encode(['code' => 400, 'msg' => '未开启AI功能']));
            }
        } else {
            $response->write('data: ' . Json::encode(['code' => 400, 'msg' => '请先登录']));
        }
    }

    #[
        GetMapping('dialogue-list'),
        Auth(label: ['Ai对话列表'], relyon: ['ai.chat'])
    ]
    public function DialogueList()
    {

    }
}